package edu.szte.ovrt.datahandler.csv;

import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

import edu.szte.ovrt.datahandler.core.AbstractDocumentReader;
import edu.szte.ovrt.datahandler.core.DocumentReaderException;
import edu.szte.ovrt.datahandler.model.Document;
import edu.szte.ovrt.datahandler.model.Section;

public class CSVReader extends AbstractDocumentReader {

	public CSVReader(final Reader reader) {
		super(reader);
	}

	@Override
	public Document readDocument() throws DocumentReaderException {
		final Document retDoc = new Document();

		try {
			String line;
			Section section = null;
			// read document
			while ((line = m_reader.readLine()) != null) {
				if (!line.contains(";")) {
					// create new section
					section = retDoc.newSection(line);
				} else if (section != null && line.contains(";")) {
					// this line is an item -> scan it
					final Scanner lineScanner = new Scanner(line);
					lineScanner.useDelimiter(";");
					section.newItem(lineScanner.next(), lineScanner.next());
				} else {
					// if something isn't proper
					throw new DocumentReaderException("The file isn't a proper csv file!");
				}
			}
		} catch (final IOException e) {
			throw new DocumentReaderException(e);
		}

		return retDoc;
	}
}
